<?php

// Storage in php files

class storage_php extends storage {

	function put($path, $data, $expires = false)
	{
		$path = realpath($this->config['path'].'/'.$path);
		$dir = dirname($path);
		
		if(!file_exists($dir)) 
		{
			if(!mkdir($dir, 0777, true)) //tries to create dir
			{
				error::new('cannot create directory: '.$dir,E_ERROR,debug_backtrace());
				return false;
			}
		}
		
		$file = tempnam($dir, 'tmp_'); //create temporary file
		
		if(!file_put_contents($file, "<?php \r\n".'$data = '.var_export($data).";\r\n ?>"))
		{
			error::new('file_put_contents: '.$path,E_ERROR, debug_backtrace());
			return false;
		}
		else
		{
			if(!rename($file,$path)) // move to path to update/write new file
			{
				error::new('rename: '.$file.' -> '.$path,E_ERROR, debug_backtrace());
				unlink($file);
				return false;
			}
		}
		
		if(!empty($expires))
		{
			if(!touch($path,$expires))
			{
				error::new('touch: '.$path,E_ERROR,debug_backtrace());
				return false;
			}
		}
		
		return true;
	}
	
	function get($path, $check_expired = false)
	{
		$path = realpath($this->config['path'].'/'.$path);
		if (!file_exists($path) return false;
		if($check_expired && ((filemtime($path) - time()) < 0))
		{
			unlink($path);
			return false;
		}
		
		include_once($path);
		return $data;
	}
	
	function rm($path)
	{
		return unlink($path);
	}
	
	function gc()
	{
		//scan dir config['path'], remove expired files
	}
	
	function flush()
	{
		rmdir($this->config['path']);
		mkdir($this->config['path']);
	}
	
	

}

?>